package ajax;

import helpers.StringHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;

import models.UserModel;

import data.UserData;
import forms.UserForm;

public class LoginAjaxServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		HttpSession session = request.getSession();
		
		UserData userData = new UserData();
		UserModel user = new UserModel();
		UserForm userForm = new UserForm();
		
		TreeMap form = (TreeMap) userForm.checkLogin(request, user);
		
		user = (UserModel) form.get("user");
		TreeMap check = (TreeMap) form.get("checkValid");
		
		if (check.size() == 0) {
			UserModel user_login = userData.getUser(user.getUsername());
			if (user_login != null) {
				if (user_login.getPassword().equalsIgnoreCase(StringHelper.md5(user.getPassword()))) {
					if (user_login.getStatus() == 2) {
						//Save login to session
						session.setAttribute("user_logged_in", user_login);
						check.put("success", true);
					} else {
						check.put("email", "Tài khoản bạn chưa được kích hoạt hoặc đang bị khóa.");
						check.put("success", false);
					}
				} else {
					check.put("password", "Mật khẩu không đúng");
					check.put("success", false);
				}
			} else {
				check.put("email", "Email truy cập không tồn tại.");
				check.put("success", false);
			} 
		} else {
			check.put("success", false);
		}
		
		String json = new Gson().toJson(check);
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json);
		
	}
}
